//
//  BSSpriterData.m
//  Spriter_forCocs2d
//
//  Created by Yang Bean on 13/4/19.
//
//
#import "BSBoneRef.h"
#import "BSBone.h"
#import "BSSpriterData.h"
#import "BSFolder.h"
#import "BSFile.h"
#import "BSAnimation.h"
#import "BSTimeLine.h"
#import "BSObject.h"
#import "cocos2d.h"
#import "BSMainLine.h"
#import "BSKey.h"
#import "BSKeyRef.h"
#import "BSObjectRef.h"
#import <Foundation/NSString.h>
#define NO_PARENT -1



using namespace cocos2d;
@interface BSSpriterData()

@end

@implementation BSSpriterData
@synthesize folders = m_folders;
@synthesize animations = m_animations;
CCPoint toCCPoint(CGPoint cgp)
{
    return ccp(cgp.x, cgp.y);
}
- (NSString *)description
{
    return [NSString stringWithFormat:@"folder = %@, animation = %@",
            m_folders, m_animations];
}

- (BSFile*)fileWithFolderId:(int)folderId fileid:(int)fileId
{
    BSFolder* folder = [m_folders objectForKey:[NSString stringWithFormat:@"%d", folderId]];
    BSFile* file = [folder.files objectForKey:[NSString stringWithFormat:@"%d", fileId]];
    return file;
}
- (BSAnimation*)animationWithAnimationId:(int)animId
{
    return [m_animations objectForKey:[NSString stringWithFormat:@"%d", animId]];
}
- (BSAnimation*)animationWithAnimationName:(NSString*)animName
{
    NSEnumerator *enumerator = [m_animations keyEnumerator];

    id aKey = nil;
    while ( (aKey = [enumerator nextObject]) != nil) {
        BSAnimation* animation = [m_animations objectForKey:aKey];
//        NSLog(@"count = %d", [animation retainCount]);
//        NSLog(@"%@ = animation name", [animation name]);
        if ([[animation name] isEqualToString:animName])
        {
            return animation;
        }
    }
    NSLog(@"can not find animation");
    return nil;
}

////////////////////////////////////////////////////////
//z
////////////////////////////////////////////////////////
- (NSArray*)zOrdersWithTimelineID:(int)tlid inMainLine:(BSMainLine*)mainLine
{
    NSMutableArray* array = [NSMutableArray array];
    
    for (int i = 0; i < [[mainLine keyRefs] count]; i++)
    {
        int z = [self zOrderWithKeyId:i timelineID:tlid inMainLine:mainLine];
        NSLog(@"z = %d", z);
        NSNumber* number = [NSNumber numberWithInt:z];
        [array addObject:number];
    }
    return array;
}
////////////////////////////////////////////////////////
//z
////////////////////////////////////////////////////////
- (int)zOrderWithKeyId:(int)keyId timelineID:(int)tlid inMainLine:(BSMainLine*)mainLine
{
    BSKeyRef* keyRef = [mainLine.keyRefs objectForKey:[NSString stringWithFormat:@"%d", keyId]];
    return [self zOrderWithKeyRef:keyRef timelineID:tlid];
}
////////////////////////////////////////////////////////
//z
////////////////////////////////////////////////////////
- (int)zOrderWithKeyRef:(BSKeyRef*)keyRef timelineID:(int)tlid
{
    if (keyRef) {
        for (int i = 0; i < [keyRef.objRefArray count] ; i++) {
            BSObjectRef* objRef = [keyRef.objRefArray objectAtIndex:i];
            if (objRef.timeline == tlid) {
                return objRef.z;
            }
        }
    }
    NSLog(@"error in z order");
    return 0;
}

////////////////////////////////////////////////////////
//設定動畫
////////////////////////////////////////////////////////
- (void)setAnimation:(BSAnimation*)animation 
        toTimeLineId:(int)timelindId
              sprite:(cocos2d::CCSprite*)sprite
            isRepeat:(BOOL)isRepeat
{
    NSDictionary* dict = [[animation timelinsWithTimelineID:timelindId] objs];
    BSObject* lastObj = [dict objectForKey:[NSString stringWithFormat:@"%d", 0]];
    

    cocos2d::CCArray* scaleArray = cocos2d::CCArray::create();
    cocos2d::CCArray* moveArray = cocos2d::CCArray::create();
    cocos2d::CCArray* rotateArray = cocos2d::CCArray::create();
    cocos2d::CCArray* alphaArray = cocos2d::CCArray::create();
    for (int i = 1; i < [dict count]; i++)
    {
        BSObject* obj = [dict objectForKey:[NSString stringWithFormat:@"%d", i]];
        float time = ((float)obj.time - (float)lastObj.time) / 1000;

        cocos2d::CCMoveTo* move = cocos2d::CCMoveTo::create(time, toCCPoint([obj point]));
        moveArray->addObject(move);
        

        cocos2d::CCScaleTo* scale = cocos2d::CCScaleTo::create(time, [obj scale].x, [obj scale].y);
        scaleArray->addObject(scale);
        
        
        int angle = obj.angle;
        cocos2d::CCRotateTo* rotate = cocos2d::CCRotateTo::create(time, -angle);
        rotateArray->addObject(rotate);
        
        cocos2d::CCFadeTo* alpha = cocos2d::CCFadeTo::create(time, [obj alpha]);
        alphaArray->addObject(alpha);
        
        lastObj = obj;
    }
    
    [self setSprite:sprite ActWithActArray:rotateArray Repeat:isRepeat];
    [self setSprite:sprite ActWithActArray:moveArray Repeat:isRepeat];
    [self setSprite:sprite ActWithActArray:scaleArray Repeat:isRepeat];
    [self setSprite:sprite ActWithActArray:alphaArray Repeat:isRepeat];

}
- (void)setSprite:(cocos2d::CCSprite*)sprite
       ActWithActArray:(cocos2d::CCArray*)array
                Repeat:(BOOL)isRepeat
{
    if (array->count() <= 0) return;
    
    if (isRepeat)
    {
        CCFiniteTimeAction* seqAct = cocos2d::CCSequence::create(array);
        cocos2d::CCRepeatForever* repeat = cocos2d::CCRepeatForever::create((cocos2d::CCActionInterval*)seqAct);
        sprite->runAction(repeat);
    }
    else
    {
        
        sprite->runAction(cocos2d::CCSequence::create(array));
    }
}
////////////////////////////////////////////////////////
//parentId
////////////////////////////////////////////////////////
- (int)parentIdWithKeyId:(int)keyId timelineID:(int)tlid inMainLine:(BSMainLine*)mainLine
{
    BSKeyRef* keyRef = [mainLine.keyRefs objectForKey:[NSString stringWithFormat:@"%d", keyId]];
    for (int i = 0; i < [keyRef.bonRefeArray count]; i++) {
        BSBoneRef* boneRef = [keyRef.bonRefeArray objectAtIndex:i];
        if (boneRef.timelineID == tlid) {
            return boneRef.parentBoneID;
        }
    }
    return NO_PARENT;
}
////////////////////////////////////////////////////////
//sprite
////////////////////////////////////////////////////////
- (cocos2d::CCArray*)spriteArrayWithAniamtionName:(NSString*)name
{
    return [self spriteArrayWithAniamtion:[self animationWithAnimationName:name]];
}
- (cocos2d::CCArray*)spriteArrayWithAniamtion:(BSAnimation*)animation
{
    cocos2d::CCArray* array = cocos2d::CCArray::create();
    NSArray* timelineArray = [animation timelines];
    for (int i = 0; i < [timelineArray count]; i++)
    {
        BSTimeLine* timeline = [timelineArray objectAtIndex:i];
        if (timeline.objs)
        {
            BSObject* obj = [[timeline objs] objectForKey:[NSString stringWithFormat:@"%d", 0]];
            BSFile* file = [self fileWithFolderId:[obj folder] fileid:[obj file]];
            NSString* fn = [file name];
            cocos2d::CCSprite* sprite = cocos2d::CCSprite::create([fn UTF8String]);
            
            array->addObject(sprite);
            sprite->setPosition(toCCPoint([obj point]));
            sprite->setAnchorPoint(toCCPoint([obj pivot]));
            sprite->setScaleX([obj scale].x);
            sprite->setScaleY([obj scale].y);
            sprite->setRotation(-[obj angle]);
            sprite->setTag([timeline timelineId]);
            sprite->setOpacity([obj alpha]);
        }
    }
    return array;
}
- (cocos2d::CCArray*)spriteArrayWithAniamtion:(BSAnimation*)animation
                                       shield:(NSString*)shield
                                          hat:(NSString*)hat
                                       weapon:(NSString*)weapon
                                         race:(NSString*)race
{
    cocos2d::CCArray* array = cocos2d::CCArray::create();
    NSArray* timelineArray = [animation timelines];
    for (int i = 0; i < [timelineArray count]; i++)
    {
        BSTimeLine* timeline = [timelineArray objectAtIndex:i];
        if (timeline.objs)
        {
            BSObject* obj = [[timeline objs] objectForKey:[NSString stringWithFormat:@"%d", 0]];
            BSFile* file = [self fileWithFolderId:[obj folder] fileid:[obj file]];
            NSString* fn = [file name];
            if ([fn isEqualToString:@"shield/shield.png"])
                fn = [fn stringByReplacingOccurrencesOfString:@"shield" withString:shield];
            else if ([fn isEqualToString:@"hat/helmet.png"])
                fn = [fn stringByReplacingOccurrencesOfString:@"helmet" withString:hat];
            else if ([fn isEqualToString:@"weapon/stick.png"])
                fn = [fn stringByReplacingOccurrencesOfString:@"stick" withString:weapon];
            else
                fn = [fn stringByReplacingOccurrencesOfString:@"orc" withString:race];
            NSLog(@"%@", fn);
            cocos2d::CCSprite* sprite = cocos2d::CCSprite::create([fn UTF8String]);
            
            array->addObject(sprite);
            sprite->setPosition(toCCPoint([obj point]));
            sprite->setAnchorPoint(toCCPoint([obj pivot]));
            sprite->setScaleX([obj scale].x);
            sprite->setScaleY([obj scale].y);
            sprite->setRotation(-[obj angle]);
            sprite->setTag([timeline timelineId]);
            sprite->setOpacity([obj alpha]);
        }
    }
    return array;
}

- (void)dealloc
{
    [super dealloc];
}
@end
